package com.qf.air.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.qf.air.vo.R;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传&下载
 * @author zjw
 * @description
 * @date 2021/10/9 17:01
 */
@RestController
public class UploadController {

    /**
     * 引用加载过的properties文件中的value
     */
    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${oss.bucketName}")
    private String bucketName;


    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        // 保存文件（本地）
        // 获取文件的原名字
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成新文件名
        String newName = UUID.randomUUID().toString() + suffixName;
        // 保存到本地
        // file.transferTo(new File("D://pic//" + newName));
        String s = Base64.encodeBase64String(file.getBytes());
        System.out.println(s);
        //====================================================================
        // 保存文件到阿里云的OSS
        // 1. 构建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 2. 上传文件到OSS服务器
        ossClient.putObject(bucketName,newName,file.getInputStream());
        // 3. 声明文件访问地址
        String url = "https://" + bucketName + "." + endpoint + "/" + newName;

        System.out.println("图片路径 = " + url);

        return R.ok();
    }


    @PostMapping("/uploadBase64")
    public R upload(String file,String suffix){
        byte[] bytes = Base64.decodeBase64(file);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        // 1. 构建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 2. 上传文件到OSS服务器
        String newName = UUID.randomUUID().toString() + suffix;
        ossClient.putObject(bucketName,newName,inputStream);
        // 3. 声明文件访问地址
        String url = "https://" + bucketName + "." + endpoint + "/" + newName;
        return R.ok();
    }

    @GetMapping("/download/{name:.+}")
    public void download(@PathVariable String name, HttpServletResponse resp) throws IOException {
        // 获取到文件流
        FileInputStream inputStream = new FileInputStream("D:\\pic\\" + name);

        // 设置响应头，要求以附件的形式打开
        resp.setHeader("Content-Disposition","attachment; fileName=" + name);

        // 获取到输出流
        ServletOutputStream outputStream = resp.getOutputStream();

        // 写回流
        IOUtils.copy(inputStream,outputStream);
    }

}
